# --------------------------------------------------------------------------------------------------------------------------
# =====================================
# ========== Guidelines ===============
# =====================================
#
# -------------------------------------
# ---- Common Environment Variable ----
# -------------------------------------
# ${Package_Publish} (boolean): Indicates whether it is build package process, e.g. If you want to get one CI SDK package.
# ${Clean_Clone} (boolean): Indicates whether it is clean build. If true, CI will clean ${output} for each build process.
# ${is_tag_fetch} (boolean): If true, git checkout will work as tag fetch mode.
# ${is_official_build} (boolean): Indicates whether it is official build release.
# ${arch} (string): Indicates build arch set in build pipeline.
# ${short_version} (string): CI auto generated short version string.
# ${release_version} (string): CI auto generated version string.
# ${build_date} (string(yyyyMMdd)): Build date generated by CI.
# ${build_timestamp} (string (yyyyMMdd_hhmm)): Build timestamp generated by CI.
# ${platform} (string): Build platform generated by CI.
# ${BUILD_NUMBER} (string): Build number generated by CI.
# ${WORKSPACE} (string): Working dir generated by CI.
#
# -------------------------------------
# ------- Job Custom Parameters -------
# -------------------------------------
# If you added one custom parameter via rehoboam website, e.g. extra_args.
# You could use $extra_args to get its value.
#
# -------------------------------------
# ------------- Input -----------------
# -------------------------------------
# ${source_root}: Source root which checkout the source code.
# ${WORKSPACE}: project owned private workspace.
#
# -------------------------------------
# ------------- Output ----------------
# -------------------------------------
# Generally, we should put the output files into ${WORKSPACE}
# 1. for pull request: Output files should be zipped to test.zip, and then copy to ${WORKSPACE}.
# 2. for pull request (options): Output static xml should be static_${platform}.xml, and then copy to ${WORKSPACE}.
# 3. for others: Output files should be zipped to anything_you_want.zip, and then copy it to {WORKSPACE}.
#
# -------------------------------------
# --------- Avaliable Tools -----------
# -------------------------------------
# Compressing & Decompressing: 7za a, 7za x
#
# -------------------------------------
# ----------- Test Related ------------
# -------------------------------------
# PR build, zip test related to test.zip
# Package build, zip package related to package.zip
#
# -------------------------------------
# ------ Publish to artifactory -------
# -------------------------------------
# [Download] artifacts from artifactory:
# python3 ${WORKSPACE}/artifactory_utils.py --action=download_file --file=ARTIFACTORY_URL
#
# [Upload] artifacts to artifactory:
# python3 ${WORKSPACE}/artifactory_utils.py --action=upload_file --file=FILEPATTERN --project
# Sample Code:
# python3 ${WORKSPACE}/artifactory_utils.py --action=upload_file --file=*.zip --project
#
# [Upload] artifacts folder to artifactory
# python3 ${WORKSPACE}/artifactory_utils.py --action=upload_file --file=FILEPATTERN --project --with_folder
# Sample Code:
# python3 ${WORKSPACE}/artifactory_utils.py --action=upload_file --file=./folder --project --with_folder
#
# ========== Guidelines End=============
# --------------------------------------------------------------------------------------------------------------------------

echo Package_Publish: $Package_Publish
echo is_tag_fetch: $is_tag_fetch
echo arch: $arch
echo source_root: ${source_root}
echo output: /tmp/jenkins/${project}_out
echo build_date: $build_date
echo build_time: $build_time
echo release_version: $release_version
echo short_version: $short_version
echo sdk_url: $sdk_url
echo toolbox_url: $toolbox_url
echo dev_env_config_url: $dev_env_config_url
echo pwd: `pwd`


# enter android project direction
cd Android

# Set up JDK environment
SYSTEM=$(uname -s)
if [ "$SYSTEM" = "Linux" ];then
  if [ ! -d "/tmp/jdk-17.0.2" ];then
    curl -O https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-x64_bin.tar.gz
    tar zxf openjdk-17.0.2_linux-x64_bin.tar.gz
    mv jdk-17.0.2 /tmp/
  fi
  export JAVA_HOME=/tmp/jdk-17.0.2
  export ANDROID_HOME=/usr/lib/android_sdk
elif [ "$SYSTEM" = "Darwin" ];then
  export JAVA_HOME=$(/usr/libexec/java_home -v 17)
  export ANDROID_HOME=${ANDROID_HOME:-$HOME/Library/Android/sdk}
fi

export PATH=$JAVA_HOME/bin:$PATH
java --version || { echo "Error: Failed to get Java version"; exit 1; }

# Configure environment
if [ "$SYSTEM" = "Linux" ];then
  [ -f ~/.bashrc ] && source ~/.bashrc
else
  # Try to load zsh config first, if not found then try bash_profile
  if [ -f ~/.zshrc ]; then
    source ~/.zshrc
  elif [ -f ~/.bash_profile ]; then
    source ~/.bash_profile
  fi
fi

# Set up Gradle directory
#[ ! -d ~/.gradle ] && mkdir -p /tmp/.gradle && ln -s /tmp/.gradle ~/.gradle && touch ~/.gradle/ln_$(date "+%y%m%d%H")
echo "ANDROID_HOME: $ANDROID_HOME"

sed -ie "s#google()#maven { url \"https\://maven.aliyun.com/repository/public\" }\n        google()#g" settings.gradle
sed -ie "s#https://services.gradle.org/distributions#https://mirrors.cloud.tencent.com/gradle#g" gradle/wrapper/gradle-wrapper.properties

# download environment configuration file
echo "Start downloading environment config file..."
mkdir -p app/src/main/assets

# ensure dev_env_config_url contains https:// prefix
if [[ "${dev_env_config_url}" != *"https://"* ]]; then
  # if URL doesn't contain https:// prefix, add it
  dev_env_config_url="https://${dev_env_config_url}"
  echo "Added https prefix to config file URL: ${dev_env_config_url}"
fi

curl -L -v -H "X-JFrog-Art-Api:${JFROG_API_KEY}" -o app/src/main/assets/dev_env_config.json "${dev_env_config_url}" || exit 1
echo "Environment config file download completed, saved to app/src/main/assets/dev_env_config.json"

# download native sdk if need
if [[ ! -z ${sdk_url} && "${sdk_url}" != 'none' ]]; then
    zip_name=${sdk_url##*/}
    echo "Start downloading SDK..."
    curl -L -v -H "X-JFrog-Art-Api:${JFROG_API_KEY}" -O $sdk_url || exit 1
    7za x ./$zip_name -y

    unzip_name=`ls -S -d */ | grep Agora`
    echo unzip_name: $unzip_name

    mkdir -p common/agora-sdk

    echo source sdk path: "${unzip_name}rtc/sdk/"
    cp -a ${unzip_name}rtc/sdk/. common/agora-sdk/
    ls common/agora-sdk/

    # config app global properties
    sed -ie "s#$(sed -n '/USE_LOCAL_SDK/p' gradle.properties)#USE_LOCAL_SDK=true#g" gradle.properties
fi

# config app global properties
# select corresponding APP_ID based on toolbox_url keywords
if [[ "${toolbox_url}" != *"https://"* ]]; then
  # if URL doesn't contain https:// prefix, add it
  toolbox_url="https://${toolbox_url}"
  echo "Added https prefix: ${toolbox_url}"
fi

if [[ "${toolbox_url}" == *"staging"* ]]; then
  echo "Using staging environment APP_ID (staging)"
  APP_ID_VAR=${APP_ID_STAGING}
elif [[ "${toolbox_url}" == *"dev"* ]]; then
  echo "Using dev environment APP_ID (dev)"
  APP_ID_VAR=${APP_ID_DEV}
else
  echo "Using production environment APP_ID (prod)"
  APP_ID_VAR=${APP_ID_PROD}
fi

sed -ie "s#$(sed -n '/AG_APP_ID/p' gradle.properties)#AG_APP_ID=${APP_ID_VAR}#g" gradle.properties
sed -ie "s#$(sed -n '/TOOLBOX_SERVER_HOST/p' gradle.properties)#TOOLBOX_SERVER_HOST=${toolbox_url}#g" gradle.properties
cat gradle.properties

# Compile apk
./gradlew clean || exit 1
./gradlew :app:assembleRelease || exit 1

# Upload apk
rm -rf ${WORKSPACE}/*.apk && cp app/build/outputs/apk/china/release/*.apk ${WORKSPACE}